<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>验证文件大小</title>
</head>

<body>
  <div>
    <h1>检查文件大小</h1>
    <input type="file" id="file-uploader">
    <div id="feedback"></div </div>
</body>
<script>
  /*
  如我们所见，我们可以读取文件的大小元数据，实际上可以将其用于文件大小验证，
  您可能允许用户上传最大1MB的图像文件。让我们看看如何实现这一目标。
  */

  /* 
  // 文件上传change事件的侦听器
  fileUploader.addEventListener('change', (event) => {
    // 读取文件大小
    const file = event.target.files[0];
    const size = file.size;

    let msg = '';

    // 检查文件大小是否大于1MB，并准备一条消息。
    if (size > 1024 * 1024) {
      msg = `<span style="color:red;">The allowed file size is 1MB. The file you are trying to upload is of ${returnFileSize(size)}</span>`;
    } else {
      msg = `<span style="color:green;"> A ${returnFileSize(size)} file has been uploaded successfully. </span>`;
    }

    // 向用户显示消息
    feedback.innerHTML = msg;
  });
  */

  

  const fileUploader = document.getElementById('file-uploader');
  const feedback = document.getElementById('feedback');

  fileUploader.addEventListener('change', (event) => {
    const file = event.target.files[0];
    console.log('file', file);

    const size = file.size;
    console.log('size', size);
    let msg = '';

    if (size > 1024 * 1024) {
      msg = `<span style="color:red;">The allowed file size is 1MB. The file you are trying to upload is of ${returnFileSize(size)}</span>`;
    } else {
      msg = `<span style="color:green;"> A ${returnFileSize(size)} file has been uploaded successfully. </span>`;
    }
    feedback.innerHTML = msg;
  });

  function returnFileSize(number) {
    if (number < 1024) {
      return number + 'bytes';
    } else if (number >= 1024 && number < 1048576) {
      return (number / 1024).toFixed(2) + 'KB';
    } else if (number >= 1048576) {
      return (number / 1048576).toFixed(2) + 'MB';
    }
  }
</script>

</html>